package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    UserServiceImpl userService;

    @Override
    public Result Followed(Long followedId, boolean isFollow) {
        //1.获取登录用户id和用户对应的key
        final Long userId = UserHolder.getUser().getId();
        String key = "follow:user" + userId;
        //2.如果true，创建数据
        if(isFollow){
            //将数据存入数据库中
            final boolean save = save(new Follow(null, userId, followedId, LocalDateTime.now()));
            if(!save){
                return Result.fail("用户关注失败");
            }else{
                //如果数据库中数据存入成功就将数据再存入redis中
                // 存放登入用户的关注用户id
                stringRedisTemplate.opsForSet().add(key,followedId.toString());
            }
        }else {
            //3。如果false，删除数据 delete from tb_follow where user_id
            final boolean remove = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followedId));
            if(remove){
                //将redis中的内容也进行删除
                stringRedisTemplate.opsForSet().remove(key,followedId.toString());
            }
        }
        return Result.ok();
    }

    public Result isFollow(Long followedId) {
        //1.获取登录用户id
        final Long userId = UserHolder.getUser().getId();
        //2.查询redis是否存在字段
        /*final Integer count = query().eq("user_id", userId).eq("follow_user_id", followedId).count();*/
        String key = "follow:user" + userId;
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, followedId.toString());
        //3.如果存在，返回true
        //4。如果不存在，返回false
        if(member!=null){
            if(!member){
                //查询数据库
                final Integer count = query().eq("user_id", userId).eq("follow_user_id", followedId).count();
                return Result.ok(count>0);
            }
            return Result.ok(member);
        }else{
            return Result.fail("出现异常");
        }

    }

    @Override
    public Result isCommon(Long targetId) {
        //1.获取用户id
        final Long userId = UserHolder.getUser().getId();
        String key = "follow:user" + userId;
        String key2 = "follow:user" + targetId;
        //2.使用set集合查询用户和目标用户共同关注(交集）
        final Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if(intersect==null || intersect.size() == 0){
            return Result.ok();
        }
        //3.如果存在交集
        //3.将set集合转换成list<long>集合表示用户id
        final List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        //根据ids集合查询数据库
        final List<User> users = userService.listByIds(ids);
        final List<UserDTO> userDTOs = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOs);
    }
}
